package cn.aifeix.basic.aop;

import cn.aifeix.basic.anno.LogAnno;
import cn.aifeix.org.domain.Journal;
import cn.aifeix.org.mapper.JournalMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.util.Date;

@Component
@Aspect
public class LogAop {
    @Autowired
    private JournalMapper journalMapper;

    @Pointcut("@annotation(cn.aifeix.basic.anno.LogAnno)")
    public void pointCut(){}

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint pjp){
        // 获取ip
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknow".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length () == 0 || "unknown".equalsIgnoreCase (ip)) {
            ip = request.getHeader ("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length () == 0 || "unknown".equalsIgnoreCase (ip)) {
            ip = request.getRemoteAddr ();
            if (ip.equals ("0:0:0:0:0:0:0:1")) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost ();
                } catch (Exception e) {
                    e.printStackTrace ();
                }
                ip = inet.getHostAddress ();
            }
        }
        String url = request.getRequestURL().toString();
        // 获取到所有的方法
        MethodSignature signature = (MethodSignature)pjp.getSignature();
        Method method = signature.getMethod();
        LogAnno annotation = method.getAnnotation(LogAnno.class);
        String method1 = annotation.method();
        String methodDes = annotation.methodDes();

        // 执行业务方法
        Object proceed = null;
        try {
            proceed = pjp.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        // 添加日志
        Journal journal = new Journal(method1, methodDes, new Date(), ip, url);
        journalMapper.add(journal);
        return proceed;


    }
}
